<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /* 
            时间：O(N^2)
            空间：O(N)
        */
        function TreeNode(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new TreeNode(5)
        var b = new TreeNode(4)
        var c = new TreeNode(6)
        var d = new TreeNode(null)
        var e = new TreeNode(null)
        var f = new TreeNode(3)
        var g = new TreeNode(7)

        var h = new TreeNode(0)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g
        // 中序遍历，必须返回有序的数，才是二叉搜索树
        // 二叉搜索树就是左边的都比根节点小，右边的都比根节点大
        var isValidBST = function (root) {
            // 退出条件
            let pre = null
            function inOrder (root) {
                // 如果节点为空，也返回true
                if (!root) return true
                
                // 左
                let left = inOrder(root.left)
                // 中
                if (pre && pre.val >= root.val) return false
                pre = root
                // 右
                let right = inOrder(root.right)
                return left && right
            }
            return inOrder(root)
        };
        // console.log(isValidBST(a));
        console.log(isValidBST(h));
    </script>
</body>

</html>